package com.yx.vectordb.impl;

import cn.hutool.core.bean.BeanDesc;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.PropDesc;
import lombok.Builder;
import lombok.Data;
import lombok.experimental.Accessors;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Data
@Accessors(chain = true)
@Builder
public class MetaTable {
    private String name;
    private List<Column> columnList = new ArrayList<>();
    public static MetaTable fromBean(Class beanClass){
        BeanDesc beanDesc = BeanUtil.getBeanDesc(beanClass);
        MetaTable.MetaTableBuilder tableBuilder = MetaTable.builder();
        tableBuilder.name(beanClass.getSimpleName());
        Collection<PropDesc> props = beanDesc.getProps();
        List<Column> columns = new ArrayList<>();

        for(PropDesc propDesc:props){
            if("id".equals(propDesc.getFieldName())||"vectorId".equals(propDesc.getFieldName())){
                continue;
            }
            Column column = new Column();
            column.setName(propDesc.getFieldName());
            if(isString(propDesc.getFieldType())){
                column.setType("CHARACTER VARYING");
            }else if(isReal(propDesc.getFieldType())){
                column.setType("DOUBLE PRECISION");
            }else if(isInteger(propDesc.getFieldType())){
                column.setType("BIGINT");
            }
            columns.add(column);
            column.setBeanType(propDesc.getFieldType().getTypeName());
        }
        tableBuilder.columnList(columns);
        return tableBuilder.build();
    }

    private static boolean isInteger(Type fieldType) {
        return "java.lang.Integer".equals(fieldType.getTypeName())||"java.lang.Long".equals(fieldType.getTypeName())||"java.lang.Short".equals(fieldType.getTypeName());
    }

    private static boolean isReal(Type fieldType) {
        return "java.lang.Float".equals(fieldType.getTypeName())||"java.lang.Double".equals(fieldType.getTypeName());
    }

    private static boolean isString(Type fieldType) {
        return "java.lang.String".equals(fieldType.getTypeName());
    }




}

